<template>
    <div class="emergencyReport">
        <div class="title">
            <!-- {{typeName1}} -->
            突发事件专题报告
        </div>
        <div class="selectPanel" v-if="isSelectPanel">
            <!-- <el-select v-model="radius" 
            @change="selectChange"
            placeholder="请选择距离">
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
            </el-select> -->
            <div class="yingxiangR">
                <div>影响范围半径：</div>
                <el-input-number v-model="radius" size="small" controls-position="right" @change="selectChange" :min="1" ></el-input-number>
            </div>
            <div class="selectPanelClose"
            @click="selectPanelClose">
                X
            </div>
            <!-- <div v-for="(item,index) in ziyuanList" :key="index">
                {{item}}
            </div> -->
            <div class="jianbaoExport" @click="changeReport('简报',currentItem)">
                生成简报
            </div>
        </div>
        <div class="emergencyEvents">
            <div class="conditionBox">
                <!-- 时间 -->
                <el-date-picker
                    popper-class="eventTimePicker"
                    v-model="dateRange"
                    type="daterange"
                    value-format="YYYY-MM-DD"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
                <!-- 区划 -->
                <div class="area" v-if="$store.state.userRegion=='海南省'">
                    <span>区划:</span>
                    <el-select v-model="eventAarea" 
                    placeholder="请选择区划">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                    <!-- <el-input v-model="eventAarea"></el-input> -->
                </div>
                <!-- 类型 -->
                <div class="type">
                    <el-select
                        popper-class="eventSelect"
                        v-model="eventType"
                        placeholder="请选择"
                    >
                        <el-option
                            v-for="item in typeOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        ></el-option>
                    </el-select>
                    <div class="search" @click="getEventData()">查询</div>
                </div>
            </div>
            <div class="eventBox">
                <div
                    :class="{
                        eventItem: true,
                        activeEvent: currentId === item.id,
                    }"
                    v-for="(item, index) of eventList"
                    :key="index"
                >
                    <div
                        class="eventItemSpan"
                        :title="item.title"
                        @click="flyTo(item)"
                    >
                        <span class="emergencyOrderNum">{{ index + 1 }}</span>
                        、{{ item.title }}
                    </div>
                    <div class="eventTime">
                        <!-- {{ item.updateTime.split(" ")[0].slice(5) }} -->
                        {{ item.updateTime}}
                    </div>
                    <div class="reportBtn">
                        <p @click="changeReport('专报', item)">事故专报</p>
                        <!-- <p @click="changeReport('简报', item)">作战指挥简报</p> -->
                        <p @click="flyAddPoint(item)">作战指挥简报</p>
                    </div>
                </div>
            </div>
            <div id="btnBox">
                <p @click="changeReport('专报')">专报</p>
                <p @click="changeReport('简报')">简报</p>
            </div>
            <!-- 暂时关闭，会修改事件内容 -->
            <!-- <div class="showReportBtn" @click="handleFormClick()">
                生产安全事故上报
            </div> -->
            <EventReport
                v-if="showReport === '专报'"
                :eventInfo="currentEvent"
                @closeReport="closeReport"
            ></EventReport>
            <CommandReport
                v-if="showReport === '简报'"
                :eventInfo="currentEvent"
                :radius = "radius"
                @closeReport="closeReport"
            ></CommandReport>
            <AccidentUpload
                v-if="upload"
                :eventsList="eventList"
                @close="close"
            ></AccidentUpload>
        </div>
    </div>
</template>

<script>
import axios from "axios";
import { keyFormate } from "./emergencyReport/dictionary";
import pointeManager from "../../pointTFSJ";
import doc from "../../sjzxDoc";
import EventReport from "./emergencyReport/EventReport.vue";
import CommandReport from "./emergencyReport/CommandReport.vue";
import AccidentUpload from "./emergencyReport/AccidentUpload.vue";
let handler3D = null;
let entityModel = [];
let circleEntity = []; //扩散波
let poiModel = []; //poi点
export default {
    name: "EmergencyReport",
    data() {
        return {
            eventList: [],
            currentEvent: {},
            showReport: null,
            currentId: null, //当前点击的事件id
            tempId: null,
            lastMOdel: null,
            dateRange: null, //时间区间
            eventAarea: "", //行政区划
            eventType: "", //事件类型
            typeOption: [
                // 自然灾害类:a；事故灾难：b;公共卫生事件:c;社会安全事件:d;其它突发事件:e;
                { value: "", label: "全部" },
                { value: "a", label: "自然灾害类" },
                { value: "b", label: "事故灾难" },
                { value: "c", label: "公共卫生事件" },
                { value: "d", label: "社会安全事件" },
                { value: "e", label: "其它突发事件" },
            ],
            upload: false,
            radius:3,
            options: [
                { value: "", label: "全部" },
                { value: "海口市", label: "海口" },
                { value: "万宁市", label: "万宁" },
                { value: "陵水黎族自治县", label: "陵水" },
                { value: "乐东黎族自治县", label: "乐东" },
                { value: "五指山市", label: "五指山" },
                { value: "定安县", label: "定安" },
                { value: "琼中黎族苗族自治县", label: "琼中" },
                { value: "文昌市", label: "文昌" },
                { value: "三亚市", label: "三亚" },
                { value: "琼海市", label: "琼海" },
                { value: "屯昌县", label: "屯昌" },
                { value: "儋州市", label: "儋州" },
                { value: "白沙黎族自治县", label: "白沙" },
                { value: "昌江黎族自治县", label: "昌江" },
                { value: "澄迈县", label: "澄迈" },
                { value: "保亭黎族苗族自治县", label: "保亭" },
                { value: "东方市", label: "东方" },
                { value: "临高县", label: "临高" },
                { value: "三沙市", label: "三沙" },
            ],
            currentItem:null,
            isSelectPanel:false
        };
    },
    components: {
        EventReport,
        CommandReport,
        AccidentUpload,
    },
    watch: {
        dateRange(val) {
            console.log(val);
        },
    },
    mounted() {
        this.getEventData();
    },
    methods: {
        selectChange(val){
            this.showCricle(this.currentItem)
            this.$store.commit("changeCircleRadius",val)
        },
        // 关闭报告
        closeReport() {
            this.showReport = null;
        },
        //
        flyAddPoint(item){
            console.log(item)
            this.flyTo(item);
            this.isSelectPanel = true;
            setTimeout(()=>{
                this.showCricle(item);
            },1500)
        },
        // 扩散波
        showCricle(item) {
            this.currentItem = item;
            if (circleEntity) this.hideCircle();
            // if(this.radius <= 0) return;
            let data = {
                id: item.id,
                imageUrl: "/images/fireReport/ripple.png",
                lon: item.lon,
                lat: item.lat,
                height: 0,
                minR: 100,
                maxR: this.radius * 1000,
                deviationR: this.radius * 10,
            };
            let r1 = data.minR,
                r2 = data.minR;
            function changeR1() {
                r1 = r1 + data.deviationR;
                if (r1 >= data.maxR) {
                    r1 = data.minR;
                }
                return r1;
            }
            function changeR2() {
                return r1;
            }
            circleEntity = viewer.entities.add({
                name: "",
                // id: data.id,
                position: Cesium.Cartesian3.fromDegrees(
                    data.lon,
                    data.lat,
                    data.height
                ),
                ellipse: {
                    semiMinorAxis: data.maxR,
                    semiMajorAxis: data.maxR,
                    // semiMinorAxis: new Cesium.CallbackProperty(changeR2,false),
                    // semiMajorAxis: new Cesium.CallbackProperty(changeR1,false),
                    height: data.height,
                    material: new Cesium.ImageMaterialProperty({
                        // image: data.imageUrl,
                        repeat: new Cesium.Cartesian2(1.0, 1.0),
                        transparent: true,
                        color: Cesium.Color.RED.withAlpha(0.2),
                        // color: new Cesium.CallbackProperty(function () {
                        //   return Cesium.Color.WHITE.withAlpha(1.7-r1/data.maxR)  //entity的颜色透明 并不影响材质，并且 entity也会透明哦
                        // },false)
                    }),
                },
            });
            // 添加poi点
            this.showPOI(data, "leftClick", this.handlePoiPointClick);
        },
        //
        hideCircle(){
            viewer.entities.remove(circleEntity);
            circleEntity = null;
        },
        // 渲染POI点
        async showPOI(data, eventType, event) {
            let params = { lon: data.lon, lat: data.lat, radius: data.maxR };
            let poiRes = await axios.get(
                `${window.huoqingApiUrl}/api/poi-point/nearby`,
                { params: params }
            );
            // this.selectOptions = poiRes
            // 每次更新数据，清除之前的实体
            this.hidePOI();
            poiModel = [];
            //添加标记
            for (let item of poiRes.data) {
                let entity = viewer.entities.add({
                    name: item.ppType,
                    id: item.ppId,
                    position: Cesium.Cartesian3.fromDegrees(
                        item.ppLon,
                        item.ppLat
                    ),
                    billboard: {
                        image: `./images/fireReport/poi/${item.ppGroup}_${item.ppType}.png`,
                        scale: 0.8,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        scaleByDistance: new Cesium.NearFarScalar(
                            10000,
                            1,
                            100000,
                            0.7
                        ),
                        disableDepthTestDistance: Number.POSITIVE_INFINITY,
                        width: 30,
                        height: 30,
                    },
                    entityType: "poi",
                    poiType: item.ppType,
                });
                if (eventType && event) {
                    entity[eventType] = event;
                }
                poiModel.push(entity);
            }
            // this.poiFormated = this.calPoiNum(poiRes)
            // console.log(this.poiFormated)
        },
        // 清除POI点
        hidePOI() {
            for (var i = 0; i < poiModel.length; i++) {
                viewer.entities.remove(poiModel[i]);
            }
            poiModel = [];
        },
        
        // 关闭事故上报面板
        close() {
            this.upload = false;
        },
        // 获取事件接报列表
        async getEventData() {
            //let eventRes = await axios.get('/data/event.json');
            // let eventRes = await axios.get(
            //     `${sjzxUrl}/api/disaster/all`,
            //     {}
            // );
            let disasterType = this.eventType;
            let startTime = this.dateRange
                ? `${this.dateRange[0]} 00:00:00`
                : "";
            let endTime = this.dateRange ? `${this.dateRange[1]} 00:00:00` : "";
            let area = this.$store.state.userRegion;
            if(area=="海南省"){

            }else{
                this.eventAarea = area
            }
            let xzqh = this.eventAarea;
            let eventRes = await axios.post(
                `${sjzxUrl}/api/disaster/selectByParam`,
                {
                    disasterType,
                    endTime,
                    startTime,
                    xzqh,
                }
            );
            this.eventList = eventRes.data.data;
            // console.log(eventRes.data.data);

            pointeManager.removePointByType("突发事件");
            pointeManager.createPoint(
                "突发事件",
                this.eventList,
                "详情",
                "leftClick",
                this.eventPointHandleClick
            );
        },
        eventPointHandleClick(entity) {
            if (this.lastMOdel) {
                this.lastMOdel._billboard._image._value =
                    "./images/sjzx/icons/突发事件.png";
            }
            entity._billboard._image._value =
                "./images/sjzx/icons/突发事件1.png";
            this.addBoundInfoEventBox(entity.position._value, "infoBox3");
            let obj = {};
            let dic = doc[entity.type];
            // 原顺序
            for (let key in dic) {
                obj[dic[key]] = entity.detail[key];
            }
            this.$store.commit("changeInfoBoxContent", obj);
            window.eventId = entity.id;
            this.lastMOdel = entity;
        },
        addBoundInfoEventBox(positionValue, elementId) {
            const oneDiv = window.document.getElementById(elementId);
            oneDiv.style.display = "block";
            let preRenderListener = viewer.scene.preRender.addEventListener(
                function() {
                    let elWidth = oneDiv.offsetWidth;
                    let elHeight = oneDiv.offsetHeight; // + 60
                    const scratch = new Cesium.Cartesian2(); //cesium二维笛卡尔 笛卡尔二维坐标系就是我们熟知的而二维坐标系；三维也如此
                    let position = positionValue;
                    const canvasPosition = viewer.scene.cartesianToCanvasCoordinates(
                        position,
                        scratch
                    ); //cartesianToCanvasCoordinates 笛卡尔坐标（3维度）到画布坐标
                    if (Cesium.defined(canvasPosition)) {
                        // 根据元素宽高及当前点屏幕坐标进行偏移
                        oneDiv.style.top =
                            canvasPosition.y - elHeight * 1 - 30 + "px";
                        oneDiv.style.left =
                            canvasPosition.x - elWidth / 2 + "px";
                    }
                }
            );
        },
        // 切换事件
        flyTo(data) {
            // 飞到球上的某个点
            // this.currentEvent = data;
            viewer.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                    data.lon,
                    data.lat,
                    20000
                ),
            });
        },
        // 显示报告
        changeReport(type, item) {
            // this.currentId = this.tempId;
            // document.getElementById("btnBox").style.display = "none";
            // this.currentEvent = this.eventList.filter(
            //     (ele) => ele.id === this.currentId
            // )[0];
            switch (type) {
                case "专报": {
                    axios
                        .get(`${sjzxUrl}/api/disaster/one?id=${item.id}`)
                        .then(res => {
                            this.currentEvent = res.data.data;
                            console.log(this.currentEvent)
                            this.showReport = type;
                        });
                    break;
                }
                case "简报": {
                    // 需要截图然后传过去
                    item.imgUrl = viewer.scene.canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                    this.currentEvent = item;
                    console.log(item);
                    this.showReport = type;
                    break;
                }
            }
        },
        // 拾取
        pickeFireEvent(movement) {
            let that = this;
            let pickedObject = viewer.scene.pick(movement.position);
            if (
                Cesium.defined(pickedObject) &&
                Cesium.defined(pickedObject.id) &&
                pickedObject.id.entityType === "event"
            ) {
                that.tempId = pickedObject.id.id;
                // 坐标
                const ray = viewer.camera.getPickRay(movement.position);
                const cartesian = viewer.scene.globe.pick(ray, viewer.scene);
                const zuobiao = Cesium.SceneTransforms.wgs84ToWindowCoordinates(
                    viewer.scene,
                    cartesian
                );
                const left = zuobiao.x + 20;
                const top = zuobiao.y + 20;
                that.$refs.btnBox.style.left = left + "px";
                that.$refs.btnBox.style.top = top + "px";
                that.$refs.btnBox.style.display = "block";

                // // 内容
                // that.fireId = pickedObject.id.id;
                // that.showDetail = true;
                // // 把id传递给报告
                // this.$emit('setFireId', that.fireId)
            } else {
                console.log("none");
                that.$refs.btnBox.style.display = "none";
            }
        },
        // 点位上球
        dataToEarth(data) {
            entityModel.forEach(ele => {
                viewer.entities.remove(ele);
            });
            entityModel = [];
            //添加标记
            for (let item of data) {
                if (item.lon && item.lat) {
                    let entity = viewer.entities.add({
                        name: item.title + item.id,
                        id: item.id,
                        position: Cesium.Cartesian3.fromDegrees(
                            item.lon,
                            item.lat
                        ),
                        billboard: {
                            // image: `./images/fireIcon/caodi.png`,
                            image: `./images/sjzx/icons/水库1.png`,
                            horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                            heightReference:
                                Cesium.HeightReference.CLAMP_TO_GROUND,
                            width: 41,
                            height: 53,
                            scaleByDistance: new Cesium.NearFarScalar(
                                10000,
                                1.5,
                                100000,
                                1
                            ),
                            disableDepthTestDistance: Number.POSITIVE_INFINITY,
                        },
                        entityType: "event",
                    });
                    entityModel.push(entity);
                }
            }
        },
        handleFormClick() {
            this.upload = true;
        },
        handlePoiPointClick(entity) {
            axios
                .get(`${sjzxUrl}/api/poi-point/getInfo/${entity.id}`)
                .then((res) => {
                    let poiDetail = keyFormate(entity.name, res.data);
                    poiDetail["poiNAME"] = entity.name;
                    this.$store.commit("changeInfoBoxContent", poiDetail);
                    this.addBoundPoiInfoBox(entity.position._value, "infoBox6");
                });
        },
        selectPanelClose(){
            this.isSelectPanel = false;
            this.hideCircle()
            this.hidePOI()
        },
        addBoundPoiInfoBox(positionValue, elementId) {
            const oneDiv = window.document.getElementById(elementId);
            oneDiv.style.display = "block";
            let preRenderListener = viewer.scene.postRender.addEventListener(
                function () {
                    let elWidth = oneDiv.offsetWidth;
                    let elHeight = oneDiv.offsetHeight; // + 60
                    const scratch = new Cesium.Cartesian2(); //cesium二维笛卡尔 笛卡尔二维坐标系就是我们熟知的而二维坐标系；三维也如此
                    var cartographicPosition =
                        Cesium.Ellipsoid.WGS84.cartesianToCartographic(
                            positionValue
                        ); //笛卡尔转84
                    var lat = Cesium.Math.toDegrees(
                        cartographicPosition.latitude
                    );
                    var lng = Cesium.Math.toDegrees(
                        cartographicPosition.longitude
                    );
                    var cart = new Cesium.Cartographic.fromDegrees(lng, lat); //输入经纬度
                    var h = viewer.scene.sampleHeight(cart);
                    // var promise = Cesium.sampleTerrainMostDetailed(window.dx, positions);//(地形数据，positions)
                    var positionFinal = Cesium.Cartesian3.fromDegrees(lng, lat, h); //加入高度之后，不会飘，但是不能解决地球缩放问题
                    const canvasPosition =
                        viewer.scene.cartesianToCanvasCoordinates(
                            positionFinal,
                            scratch
                        ); //cartesianToCanvasCoordinates 笛卡尔坐标（3维度）到画布坐标

                    if (Cesium.defined(canvasPosition)) {
                        // 根据元素宽高及当前点屏幕坐标进行偏移
                        oneDiv.style.top =
                            canvasPosition.y - elHeight * 1.1 + "px";
                        oneDiv.style.left =
                            canvasPosition.x - elWidth / 2 + "px";
                    }
                }
            );
        },
        
    },
    beforeUnmount() {
        pointeManager.removePointByType("突发事件");
        entityModel = [];
        this.hidePOI() 
        this.hideCircle()
    },
};
</script>
<style lang="stylus">
.eventBox::-webkit-scrollbar {
    /* 滚动条整体样式 */
    width: 5px; /* 高宽分别对应横竖滚动条的尺寸 */
    height: 1px;
}
.eventBox::-webkit-scrollbar-thumb {
    /* 滚动条里面小方块 */
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #535353;
}

.eventBox::-webkit-scrollbar-track {
    /* 滚动条里面轨道 */
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 10px;
    background: rgba(0, 0, 0, 0.5);
}

.emergencyEvents {
    .el-range-editor.el-input__inner, .el-date-editor .el-range-input {
        width: 100%;
        height: 30px;
        background: transparent;
    }
    .el-range-separator {
        color: #fff;
        height: unset;
    }

    .el-input__inner {
        height: 30px;
    }
    .el-select-dropdown__item span {
        color: #000;
    }
    .el-select {
        flex: 1;
    }
}
.eventSelect {
    .el-select-dropdown__item {
        text-align: center;

        span {
            color: #000;
        }
    }
}
.eventTimePicker {
    .el-date-range-picker__content .el-date-range-picker__header div, .el-date-table td span {
        color: #000;
    }
}
</style>
<style lang="stylus" scoped>
.emergencyReport {
    background: url('/images/sjzx/list.png') no-repeat;
    background-size: 100% 100%;
    width: vw(370);
    height: vh(555);
    margin-top: vh(15);
    overflow-y: hidden;
    .title {
        text-align: center;
        font-size: vw(16);
    }
    .themePic {
        width: 100%;
        display: grid;
        grid-template-columns: vw(122) vw(200);
        grid-row-gap: vh(20);
        grid-column-gap: vw(20);
        margin-top: vh(50);
        margin-left: vh(20);

        .themePicItem {
            display: flex;
            justify-content: space-around;
            background: url('/images/sjzx/item.png') no-repeat;
            background-size: 100% 100%;
            line-height: vh(37);
            height: vh(37);
            font-size: vw(14);
            margin-right: vw(20);
        }
    }
    .selectPanel{
        position:fixed;
        right:vw(450);
        top:vh(100);
        z-index:3;
        width:vw(300);
        height:vh(150);
        padding: vw(10);
        padding-top:vh(30)
        background: rgba(0, 0, 0, 0.5);
        .yingxiangR{
            display:flex;
        }
        .selectPanelClose{
            position:absolute;
            top:vh(10);
            right:vw(10);
        }
        .jianbaoExport{
            width:50%;
            height:vh(30);
            line-height:vh(30);
            margin: 0 auto;
            margin-top:vh(10);
            border:1px solid #ddd;
            text-align:center;
            cursor:pointer;
        }
    }
    .emergencyEvents {
        width: 100%;
        color: #fff;
        display: flex;
        height:vh(520);
        flex-direction: column;
        .conditionBox {
            padding: 10px;
            .area, .type {
                display: flex;
                justify-content: space-between;
                align-items: center;

                span {
                    width: 60px;
                }

                .search {
                    width: 60px;
                    height: 28px;
                    line-height: 28px;
                    margin-left: 10px;
                    border: 1px solid #17d0ff;
                    text-align: center;
                    cursor: pointer;
                    font-size: 16px;
                }
            }
        }
        .eventBox {
            flex: 1;
            margin: 10px;
            height: vh(280);
            text-align: left;
            overflow-y: scroll;
            color: #000;
            margin-top:0;
            .eventItem {
                overflow: hidden; // 高度塌陷
                line-height: 25px;
                font-size: 14px;
                // border-bottom: 1px dashed #ee0;
                margin-bottom: 10px;
                padding: 5px;
                padding-bottom: 10px;
                position: relative;
                background:rgba(0,0,0,.3);
                .eventItemSpan {
                    cursor: pointer;
                    overflow: hidden;
                    text-overflow:ellipsis;
                    white-space: nowrap;
                    .emergencyOrderNum {
                        display: inline-block;
                        width: 20px;
                        height: 20px;
                        line-height: 20px;
                        text-align:center;
                        background: #1296DB;
                    }
                }

                div.eventTime {
                    float: left;
                    line-height: 30px;
                }

                .reportBtn {
                    padding-right: 15px;
                    position: absolute;
                    right: 0px;
                    display: flex;
                    justify-content: flex-end;
                    p {
                        border: 1px solid #ddd;
                        font-size: 12px;
                        border-radius: 5px;
                        margin-left: 10px;
                        padding: 2px 2px;
                        cursor: pointer;
                    }
                }
            }

            .activeEvent span, .eventItem:hover span{
                color: #00e5fd;
            }
        }
        #btnBox {
            display: none;
            position: fixed;
            left: 500px;
            top: 300px;
            padding: 10px 15px;
            background: rgba(0, 20, 32, 0.8);
            border: 1px solid #0c4f55;
            color: #fff;
            line-height: vh(26);
            opacity: 0.8;
            background: #05253c;
            border: 1px solid #17d0ff;

            p {
                cursor: pointer;
            }

            p:hover {
                color: #00e5fd;
            }
        }
        .showReportBtn {
            width: 40%;
            height: vh(30);
            line-height: vh(30);
            text-align: center;
            cursor: pointer;
            border:1px solid #40BBF1;
            border-radius:5px;
            margin-left:vw(10);
        }
    }
}
</style>
